class UsersController < ApplicationController
  before_filter :find_recover, :only=>[:recover, :restore]
  
  # GET /activate/[activation_code]
  def activate
    logout_keeping_session!
    user = User.find_by_activation_code(params[:activation_code]) unless params[:activation_code].blank?
    case
    when (!params[:activation_code].blank?) && user && !user.active?
      user.activate!
      flash[:notice] = I18n.t("flash.user.activated")
      redirect_to '/login'
    when params[:activation_code].blank?
      flash[:error] = I18n.t("flash.user.missing_code")
      redirect_back_or_default('/')
    else 
      flash[:error]  = I18n.t("flash.user.activate_error")
      redirect_back_or_default('/')
    end
  end
  
  # POST /users/forget
  # POST /users/forget.js
  def forget
		@user = User.find_by_email(params[:email])
		
		respond_to do |format|
    	if !@user.nil? && @user.recover
        flash.now[:notice] = I18n.t("flash.user.forget_send")
        format.html { redirect_to login_path }
        format.js # render forget.rjs
      else
      	flash.now[:error] = I18n.t("flash.user.forget_error")
        format.html { redirect_to login_path }
        format.js # render forget.rjs
      end
    end
  end
  
  # GET /users/[:id]/recover
  # GET /users/[:id]/recover.xml
  def recover
  end
  
  # POST /users/[:id]/restore
  # POST /users/[:id]/restore.js
  def restore
    @user.password = params[:user][:password]
    @user.password_confirmation = params[:user][:password_confirmation]
    @user.crypted_password = nil
    
    respond_to do |format|
    	if @user.valid? && @user.restore
        flash[:notice] = I18n.t("flash.user.restore")
        format.html { redirect_to login_path }
        format.js # render restore.rjs
      else
      	flash[:error] = I18n.t("flash.user.restore_error")
        format.html { render :action=>"recover" }
        format.js # render restore.rjs
      end
    end
  end
  
  private
  
  def find_recover
    @user = User.find(:first, :conditions=>["recover_code = ? AND recover_expires_at > NOW()", params[:id]])
    raise ActiveRecord::RecordNotFound if @user.nil?
  end
end
